package com.symaster.common.geom.canvas.listener;

import com.symaster.common.geom.PolygonComponent;
import com.symaster.common.geom.Canvas;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

/**
 * @author yinmiao
 * @version 2022-07-14 14:12
 */
public class CanvasMouseMotionListener implements MouseMotionListener {

    private final Canvas canvas;

    public CanvasMouseMotionListener(Canvas canvas) {
        this.canvas = canvas;
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        Point pressedPoint = canvas.getPressedPoint();
        Point point = e.getPoint();

        Component component = e.getComponent();
        if (!(component instanceof PolygonComponent)) {
            return;
        }
        PolygonComponent<?> component1 = (PolygonComponent<?>) component;
        if (!component1.isSelect()) return;

        Point location = component.getLocation();

        int offsetX = (point.x - location.x) - pressedPoint.x, offsetY = (point.y - location.y) - pressedPoint.y;
        canvas.moveSelectAll(offsetX, offsetY);
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        Component componentAtPolygon = canvas.getComponentAtPolygon(e.getPoint());

        Component[] components = canvas.getComponents();
        for (Component component : components) {
            if (component instanceof PolygonComponent) {
                PolygonComponent<?> componentAtPolygon1 = (PolygonComponent<?>) component;
                if (componentAtPolygon != null && componentAtPolygon == component) {
                    componentAtPolygon1.mouseSuspensionStart();
                } else {
                    componentAtPolygon1.mouseSuspensionEnd();
                }
            }
        }
    }
}
